const fs = require('fs');
const path = require('path');
const archiver = require('archiver');
const { NodeSSH } = require('node-ssh');
let args = process.argv.splice(2),
isRollback = args.includes('rollback');
// 设置本地 dist 文件路径
const distPath = path.resolve('.', 'dist');
const root = path.resolve('.');
const ssh = new NodeSSH();

// 远程服务器配置信息
const config = require('./config');
// 本地文件上传至远程服务器
function uploadFile() {
  ssh
    .connect({
      host: config.host,
      username: config.username,
      password: config.password,
      port: 22,
    })
    .then(() => {
      ssh
        .putFile(
          `${root}/portal.zip`,
          `${config.pathUrl}/portal.zip`
        )
        .then(() => {
          console.log('The zip file is upload successful');
          remoteFileUpdate();
        })
        .catch((err) => {
          console.log('the file upload fail:', err);
          process.exit(0);
        });
    })
    .catch((err) => {
      console.log('SSH conneting fail:', err);
      process.exit(0);
    });
}

// 远端文件更新
const remoteFileUpdate = () => {
  let cmd = `rm -r portal && unzip portal.zip && rm -r portal.zip`
  ssh
    .execCommand(cmd, {
      cwd: config.pathUrl,
    })
    .then((result) => {
      if (!result.stderr) {
        process.exit(0);
      } else {
        console.log('Something wrong:', result);
        process.exit(0);
      }
    });
};

// 本地文件压缩
const zipDirector = () => {
  const output = fs.createWriteStream(`${root}/portal.zip`);
  const archive = archiver('zip', {
    zlib: { level: 9 },
  }).on('error', (err) => {
    throw err;
  });
  output.on('close', (err) => {
    if (err) {
      console.log('something error width the zip process:', err);
      return;
    }
    uploadFile();
    console.log(`${archive.pointer()} total bytes`);
    console.log(
      'archiver has been finalized and the output file descriptor has closed.'
    );
  });
  output.on('end', () => {
    console.log('Data has been drained');
  });
  archive.pipe(output);
  archive.directory(distPath, '/portal');
  archive.finalize();
};

// 回滚代码
if (isRollback) {
  remoteFileUpdate();
} else {
  // 更新代码
  zipDirector();
}